<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="物料代码" prop="materialCode">
        <el-input v-model="queryParams.materialCode" placeholder="请输入物料代码" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="收货编号" prop="receiptNumber">
        <el-input v-model="queryParams.receiptNumber" placeholder="请输入收货编号" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="物料名称" prop="materialName">
        <el-input v-model="queryParams.materialName" placeholder="请输入物料名称" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="收货状态" prop="receiptStatus">
        <el-select v-model="form.receiptStatus" placeholder="请选择收货状态" clearable>
          <el-option v-for="item in dict.type.material_receiving_status" :key="item.value" :label="item.label"
            :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="收货人姓名" prop="receiver">
        <el-input v-model="queryParams.receiver" placeholder="请输入收货人姓名" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">

      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['material:MaterialRecord:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['material:MaterialRecord:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['material:MaterialRecord:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="MaterialRecordList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="物料代码" align="center" prop="materialCode" />
      <el-table-column label="收货日期" align="center" prop="receiptDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.receiptDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="收货编号" align="center" prop="receiptNumber" />
      <el-table-column label="物料名称" align="center" prop="materialName" />
      <el-table-column label="供应商名称" align="center" prop="supplier" />
      <el-table-column label="生产厂家" align="center" prop="manufacturer" />
      <el-table-column label="厂家批号" align="center" prop="manufacturerBatchNumber" />
      <el-table-column label="生产日期" align="center" prop="productionDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.productionDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="保质期" align="center" prop="expirationDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.expirationDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="储存条件" align="center" prop="storageCondition" />
      <el-table-column label="物料规格" align="center" prop="specification" />
      <el-table-column label="收货总数量" align="center" prop="receivedQuantity" />
      <el-table-column label="拒收数量" align="center" prop="rejectedQuantity" />
      <el-table-column label="合格数量" align="center" prop="qualifiedQuantity" />
      <el-table-column label="收货状态" align="center" prop="receiptStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.material_receiving_status" :value="scope.row.receiptStatus" />
        </template>
      </el-table-column>
      <el-table-column label="收货人姓名" align="center" prop="receiver" />
      <el-table-column label="备注信息" align="center" prop="remarks" />

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['material:MaterialRecord:edit']">审核</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['material:MaterialRecord:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <!-- 关键修复：添加el-form并设置ref="form"和rules -->
      <el-form ref="form" :model="form" :rules="rules" label-width="300px">
        <div class="inspection-form">
          <div class="form-header">
            <h3>物料信息</h3>
          </div>

          <table class="form-table">
            <tbody>
              <!-- 第一行：物料名称、物料代码 -->
              <tr>
                <td class="label">物料名称</td>
                <td><el-input v-model="form.materialName" disabled /></td>
                <td class="label">物料代码</td>
                <td><el-input v-model="form.materialCode" disabled /></td>
              </tr>

              <!-- 第二行：收货编号、供应商名称 -->
              <tr>
                <td class="label">收货编号</td>
                <td><el-input v-model="form.receiptNumber" disabled /></td>
                <td class="label">供应商名称</td>
                <td><el-input v-model="form.supplier" disabled /></td>
              </tr>

              <!-- 第三行：生产厂家、厂家批号 -->
              <tr>
                <td class="label">生产厂家</td>
                <td><el-input v-model="form.manufacturer" disabled /></td>
                <td class="label">厂家批号</td>
                <td><el-input v-model="form.manufacturerBatchNumber" disabled /></td>
              </tr>

              <!-- 第四行：生产日期、保质期 -->
              <tr>
                <td class="label">生产日期</td>
                <td>
                  <el-date-picker v-model="form.productionDate" type="date" value-format="yyyy-MM-dd" disabled />
                </td>
                <td class="label">保质期</td>
                <td>
                  <el-date-picker v-model="form.expirationDate" type="date" value-format="yyyy-MM-dd" disabled />
                </td>
              </tr>

              <!-- 第五行：储存条件、物料规格 -->
              <tr>
                <td class="label">储存条件</td>
                <td><el-input v-model="form.storageCondition" disabled /></td>
                <td class="label">物料规格</td>
                <td><el-input v-model="form.specification" disabled /></td>
              </tr>

              <!-- 第六行：收货总数量、拒收数量 -->
              <tr>
                <td class="label">收货总数量</td>
                <td><el-input v-model="form.receivedQuantity" disabled /></td>
                <td class="label">拒收数量</td>
                <td><el-input v-model="form.rejectedQuantity" disabled /></td>
              </tr>

              <!-- 第七行：收货人姓名、备注信息 -->
              <tr>
                <td class="label">收货人姓名</td>
                <td><el-input v-model="form.receiver" disabled /></td>
                <td class="label">备注信息</td>
                <td><el-input v-model="form.remarks" disabled /></td>
              </tr>

              <!-- 第八行：收货状态（唯一可修改项） -->
              <tr>
                <td class="label required">收货状态</td>
                <td colspan="3">
                  <!-- 为收货状态添加prop关联验证规则 -->
                  <el-form-item prop="receiptStatus" style="margin: 0;">
                    <el-select v-model="form.receiptStatus" placeholder="请选择收货状态">
                      <el-option v-for="dict in dict.type.material_receiving_status" :key="dict.value"
                        :label="dict.label" :value="parseInt(dict.value)"></el-option>
                    </el-select>
                  </el-form-item>
                </td>
              </tr>
            </tbody>
          </table>
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>

        <div slot="footer" class="dialog-footer">

        </div>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { listMaterialRecord, getMaterialRecord, delMaterialRecord, addMaterialRecord, updateMaterialRecord } from "@/api/material/MaterialRecord";

export default {
  name: "MaterialRecord",
  dicts: ['material_receiving_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 物料记录管理表格数据
      MaterialRecordList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        materialCode: null,
        receiptNumber: null,
        materialName: null,
        receiptStatus: null,
        receiver: null,
      },
      // 表单参数
      form: {},
      // 表单校验规则
      rules: {
        receiptStatus: [
          { required: true, message: '请选择收货状态', trigger: 'change' }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询物料记录管理列表 */
    getList() {
      this.loading = true;
      listMaterialRecord(this.queryParams).then((response) => {
        this.MaterialRecordList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        materialCode: null,
        receiptDate: null,
        receiptNumber: null,
        materialName: null,
        supplier: null,
        manufacturer: null,
        manufacturerBatchNumber: null,
        productionDate: null,
        expirationDate: null,
        storageCondition: null,
        specification: null,
        receivedQuantity: null,
        rejectedQuantity: null,
        qualifiedQuantity: null,
        receiptStatus: null,
        receiver: null,
        remarks: null,
        id: null,
        isDelete: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加物料记录管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row ? row.id : (this.ids.length === 1 ? this.ids[0] : null); // 确保id是单个值
      if (!id) {
        this.$modal.msgWarning("请选择一条数据");
        return;
      }
      getMaterialRecord(id).then((response) => {
        this.form = response.data; // 确保response.data包含id
        this.open = true;
        this.title = "审核物料申请";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id !== null && this.form.id !== undefined && this.form.id !== '') {
            updateMaterialRecord(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addMaterialRecord(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除物料记录管理编号为"' + ids + '"的数据项？')
        .then(() => {
          return delMaterialRecord(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        'material/MaterialRecord/export',
        { ...this.queryParams },
        `MaterialRecord_${new Date().getTime()}.xlsx`
      );
    }
  }
};
</script>

<style scoped>
.dialog-footer {
  text-align: right;
  /* 让按钮右对齐，符合常见布局 */
  padding: 10px 20px;
  border-top: 1px solid #ebeef5;
}
</style>